<template>
  <view class="search">
    <u-search
      :placeholder="placeholder"
      v-model="name"
      shape="square"
      bg-color="#E5EAE8"
      height="80"
      :disabled="true"
      :show-action="true"
      :animation="true"
      :input-style="{marginLeft:'20rpx'}"
      :search-icon="searchSrc"
      placeholder-color="#999999"
      :action-style="{ color: '#369164', fontSize: '14px',fontWeight:'400' }"
    ></u-search>

    <picker class="picker-item" @change="handleSelectChange" :value="index" :range="options" range-key="label">
      <view class="uni-input">{{options.length ? options[index].label : ''}}</view>
    </picker>
  </view>
</template>

<script>
export default {
  name: 'pickerItem',
  emits: ['change', 'input'],
  props: {
    value: String,
    options: Array,
    placeholder: {
      type: String,
      default: '请选择煤矿名称'
    },
    changeValue: {
      type: String,
      default: 'label'
    }
  },
  data() {
    return {
      name: '',
      index: 0,
      searchSrc: require('./search_icon.svg'),
    }
  },
  methods: {
    handleSelectChange(e) {
      this.index = e.target.value
      const item = this.options[this.index]
      this.name = item.label

      let inputVal = item.label
      if (this.changeValue === 'id') inputVal = item.id

      this.$emit('input', inputVal)
      this.$emit('change', this.options[this.index])
    },
    getLabelById() {
      if (this.changeValue === 'id' && this.value) {
        const item = this.options.find(i => i.id === this.value)
        if (item) return item.label
      }
      return this.value
    }
  },
  watch: {
    options(val) {
      if (this.value && val.length) {
        const index = val.findIndex(item => {
          item.label === this.value
        })
        if (index || index !== 0) this.index = index
      }
    },
    value(val) {
      this.name = this.getLabelById()
    }
  },
  mounted() {
    this.name = this.getLabelById()
  }
}
</script>

<style lang="scss" scoped>
/* 搜索框 */
.search {
  padding: 20rpx 28rpx;
  position: relative;
}
.picker-item{
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  opacity: 0;
}
</style>
